package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Gareth Cao
 * @date 2022/4/28 10:57
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> add(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<Page<Category>> selectByPage(@RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
                                          @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        Page<Category> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        //排序
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 删除类别
     */
    @DeleteMapping
    public R<String> delete(Long id) {
        categoryService.remove(id);
        return R.success("删除成功");
    }

    /**
     * 修改分类
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");

    }

    /**
     * 在新增菜品页面用于显示菜品分类数据
     */
    @GetMapping("/list")
    public R<List<Category>> selectByType(Integer type) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        //查询条件
        queryWrapper.eq(type != null, "type", type);
        //查询结果
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
